//
//  WDEditOrderController.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2016/12/5.
//  Copyright © 2016年 王笛. All rights reserved.
//

#import "WDEditOrderController.h"
#import "WDCarTypeController.h"
#import "WDFinancialProductController.h"
#import "WDBusinessListController.h"
#import "WDCarTypeController.h"
#import "WDBusinessListController.h"
#import "WDStseries.h"
#import "WDProduct.h"
#import "WDMoneyTextField.h"
#import "LeftMenViewController.h"
#import "ControllerTool.h"
#import "WDPromptBox.h"
#import "WDCustomSheet.h"

@interface WDEditOrderController ()<UITextFieldDelegate, WDTextFieldLimitDelegate, WDCustomSheetDelegate>
@property (weak, nonatomic) IBOutlet UITextField *nameTextF;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextF;
@property (weak, nonatomic) IBOutlet WDMoneyTextField *carPriceTextF;
@property (weak, nonatomic) IBOutlet WDMoneyTextField *applyTextF;

@property (weak, nonatomic) IBOutlet UIButton *oldCarBtn;
@property (weak, nonatomic) IBOutlet UIButton *goodCarBtn;
@property (assign, nonatomic) BOOL isHaveDian;
@property (weak, nonatomic) IBOutlet UILabel *carTypeLabel;
@property (weak, nonatomic) IBOutlet UILabel *refundLabel;
@property (weak, nonatomic) IBOutlet UILabel *productLabel;
@property (weak, nonatomic) IBOutlet UILabel *businessLabel;
@property (weak, nonatomic) IBOutlet UITableViewCell *productCell;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *productRightContr;

/** 分期数组 */
@property (nonatomic, strong) NSArray *termArr;
/** 商户ID */
@property (nonatomic, strong) NSString *businessID;
/** 品牌id */
@property (nonatomic, strong) NSString *brandID;
/** 品牌名称 */
@property (nonatomic, strong) NSString *brandName;
/** 车系id */
@property (nonatomic, strong) NSString *stserID;
/** 车系名 */
@property (nonatomic, strong) NSString *stserName;

@end

@implementation WDEditOrderController

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

//设置StatusBar样式
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    
    //添加这句话，tableView就不会被遮盖
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self loadNavItemWithLeftAction:@selector(clickCancel) leftBtnImage:@"icon_back" leftBtnSelImage:@"icon_back" title:@"新建贷款" rihgtAction:@selector(clickRight) rightStr:@"完成"];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self preferredStatusBarStyle];
    
    //贷款和车价textField
    self.carPriceTextF.limit.delegate = self;
    self.carPriceTextF.limit.maxV = @"999.999";
    self.carPriceTextF.limit.digit = 3;
    
    self.applyTextF.limit.delegate = self;
    self.applyTextF.limit.maxV = @"999.999";
    self.applyTextF.limit.digit = 3;
    
    if (self.applyLoan) {
        
        if ([self.applyTextF.text isEqualToString:@""]) {
            self.applyTextF.text = self.product.financeamount_current;
        }
        self.applyTextF.placeholder = [NSString stringWithFormat:@"如%.2f-%.2f", [self.product.financeamount_start floatValue], [self.product.financeamount_end floatValue]];
        
        self.termArr = [self.product.term componentsSeparatedByString:@","];
        
        self.refundLabel.text = self.product.term_current;
        
        if ([self.product.car_type integerValue] == 0) {
            
            self.goodCarBtn.selected = YES;
            self.goodCarBtn.userInteractionEnabled = NO;
            self.oldCarBtn.userInteractionEnabled = NO;
            
        } else {
            
            self.oldCarBtn.selected = YES;
            self.goodCarBtn.userInteractionEnabled = NO;
            self.oldCarBtn.userInteractionEnabled = NO;
            
        }
        
        self.productLabel.text = [NSString stringWithFormat:@"%@ %@", self.product.parent_name, self.product.name];
        
        self.productCell.accessoryType = UITableViewCellAccessoryNone;
        
        self.productRightContr.constant = 20;
    }
    
}

#pragma mark - 点击事件
- (void)cancelBtn
{
    [self.view endEditing:YES];
}

- (IBAction)chooseCar:(id)sender {
    
    if (sender == self.oldCarBtn) {
        self.oldCarBtn.selected = !self.oldCarBtn.selected;
        self.goodCarBtn.selected = NO;
    } else {
        self.oldCarBtn.selected = NO;
        self.goodCarBtn.selected = !self.goodCarBtn.selected;
    }
    
}

//取消
- (void)clickCancel
{
    [self showAlertWithTitle:@"提醒" Message:@"您是否要放弃新建贷款？" leftStr:@"是" rightStr:@"否" leftBtnClick:^{
        [self.navigationController popViewControllerAnimated:YES];
    } rightClick:^{
        
    }];
}

//完成
- (void)clickRight
{
    [self.view endEditing:YES];
    
    if ([self.nameTextF.text isEqualToString:@""]) {
        
        [WDPromptBox showPromptBoxWithMassage:@"请输入正确的姓名"];
        
    } else if (self.phoneTextF.text.length < 11) {
        
        [WDPromptBox showPromptBoxWithMassage:@"请输入正确的手机号"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        
    } else if (!self.goodCarBtn.isSelected && !self.oldCarBtn.isSelected) {
        
        [WDPromptBox showPromptBoxWithMassage:@"请选择新车或二手车"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        
    } else if ([self.carTypeLabel.text isEqualToString:@""]) {
        
        [WDPromptBox showPromptBoxWithMassage:@"请选择品牌车系"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        
    } else if ([self.carPriceTextF.text isEqualToString:@""]) {
        
        [WDPromptBox showPromptBoxWithMassage:@"请输入正确的车辆价格"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        
    } else if ([self.productLabel.text isEqualToString:@""]) {
        
        [WDPromptBox showPromptBoxWithMassage:@"请选择金融产品"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        
    } else if ([self.carPriceTextF.text isEqualToString:@""]){
        
        [WDPromptBox showPromptBoxWithMassage:@"请输入正确的车辆价格"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        
    } else if ([self.applyTextF.text floatValue] > [self.carPriceTextF.text floatValue]) {
        
        [WDPromptBox showPromptBoxWithMassage:@"贷款额不能大于车价"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
    
    } else if ([self.businessLabel.text isEqualToString:@""]) {
        
        [WDPromptBox showPromptBoxWithMassage:@"请选择所属商户"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        
    } else if (self.oldCarBtn.selected != [self.product.car_type boolValue]){
        
        [WDPromptBox showPromptBoxWithMassage:@"车型不匹配"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        
    } else if ([self.applyTextF.text floatValue] > [self.product.financeamount_end floatValue] || [self.applyTextF.text floatValue] < [self.product.financeamount_start floatValue]) {
        
        [WDPromptBox showPromptBoxWithMassage:@"贷款额与产品不符"];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            
        });
        
    } else {//内容都填写完成，发请求，上传资料
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        
        NSDictionary *parameters = @{
                                     @"user_name":self.nameTextF.text,//用户名
                                     @"phone":self.phoneTextF.text,//手机号
                                     @"car_type":@(self.oldCarBtn.selected),//车辆类型
                                     @"brand_id":self.brandID,//品牌ID
                                     @"brand_name":self.brandName,//品牌名称
                                     @"series_id":self.stserID,//车系ID
                                     @"series_name":self.stserName,//车系名称
                                     @"car_price":self.carPriceTextF.text,//车价
                                     @"product_id":self.product.id,//产品ID
                                     @"product_name":self.productLabel.text,//产品名称
                                     @"loan_amount":self.applyTextF.text,//贷款金额
                                     @"pay_periods":self.refundLabel.text,//还款期数
                                     @"city_id":self.product.applyto_city,//城市ID
                                     @"loan_type":@1,//贷款类型
                                     @"is_throw":@0,
                                     @"supplier_id":self.businessID,//商户ID
                                     @"supplier_name":self.businessLabel.text//商户名称
                                     };
        
        NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLFinanceCtrate];
        
        [SVProgressHUD show];
        
        [manager POST:url parameters:parameters constructingBodyWithBlock:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [SVProgressHUD dismiss];
            
            NSString *errorCode;
            if ([responseObject[@"error_code"] isKindOfClass:[NSNumber class]]) {
                errorCode = [responseObject[@"error_code"] stringValue];
            } else {
                errorCode = responseObject[@"error_code"];
            }
            
            if ([errorCode isEqualToString:@"0"] ) {
                //跳转到贷款页面
                [[UIApplication sharedApplication].delegate window].rootViewController = [[ControllerTool shareOpenController] getDrawerController];
                
                LeftMenViewController *leftVC = (LeftMenViewController *)[[ControllerTool shareOpenController] getDrawerController].leftDrawerViewController;
                
                leftVC.defaultIndex = 1;
            } else {
                [WDPromptBox showPromptBoxWithMassage:responseObject[@"error_msg"]];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                });
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            //WDLog(@"%@", error);
            
        }];
        
    }
}

#pragma mark - tableView代理
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        switch (indexPath.row) {
            case 2:
            {
                //跳转到车系
                WDCarTypeController *carTypeV = [[WDCarTypeController alloc] init];
                
                //block传值
                
                __weak typeof (self)weakSelf = self;
                
                carTypeV.carType = ^(WDStseries *stseries ,NSString *carType){
                    
                    NSString *carName = [NSString stringWithFormat:@"%@ %@", carType, stseries.name];
                    
                    weakSelf.carTypeLabel.text = carName;
                    
                    weakSelf.brandName = carType;
                    
                    weakSelf.brandID = stseries.brand_id;
                    
                    weakSelf.stserID = stseries.id;
                    
                    weakSelf.stserName = stseries.name;
                    
                };
                
                
                carTypeV.view.backgroundColor = WDBackColor;
                
                [self.navigationController pushViewController:carTypeV animated:YES];
            }
                break;
                
            case 5:
            {
                //还款期数
                if(self.isApplyLoan) {//是申请贷款
                    //传过来的还款期数
                    
                    
                } else {//默认的还款期数
                    self.termArr = @[@"6", @"12",@"18",@"24",@"30",@"36",@"42",@"48",@"54",@"60"];
                }
                
                WDCustomSheet *sheet = [[WDCustomSheet alloc] initWithButtons:self.termArr isOriginal:NO];
                sheet.title = @"还款期数";
                sheet.delegate = self;
                [self.view.superview addSubview:sheet];
            }
                break;
                
            case 6://金融产品
            {
                
                if (!self.applyLoan) {
                    
                    if ([self.applyTextF.text isEqualToString:@""]) {
                        [WDPromptBox showPromptBoxWithMassage:@"请输入贷款金额"];
                    } else if ([self.applyTextF.text doubleValue] > [self.carPriceTextF.text doubleValue]) {
                        
                        [WDPromptBox showPromptBoxWithMassage:@"贷款金额不能大于车辆价格"];
                        
                    } else if ([self.refundLabel.text isEqualToString:@""]) {
                        [WDPromptBox showPromptBoxWithMassage:@"请选择还款期数"];
                        
                    } else if (!self.oldCarBtn.selected && !self.goodCarBtn.selected) {
                        [WDPromptBox showPromptBoxWithMassage:@"请选择车辆类型"];
                    } else {
                        //跳转金融产品
                        WDFinancialProductController *tempV = [[WDFinancialProductController alloc] init];
                        
                        tempV.loanProduct = YES;
                        tempV.loanAmount = self.applyTextF.text;
                        tempV.loanTerm = self.refundLabel.text;
                        tempV.loanCarType = self.oldCarBtn.selected;
                        __weak typeof (self)weakSelf = self;
                        tempV.productData = ^(WDProduct *product){
                            
                            weakSelf.product = product;
                            weakSelf.productLabel.text = [NSString stringWithFormat:@"%@ %@", product.parent_name, product.name];
                        };
                        
                        tempV.view.backgroundColor = WDBackColor;
                        
                        [self.navigationController pushViewController:tempV animated:YES];
                    }
                }
                
            }
                break;
                
            case 7:
            {
                //所属商户
                WDBusinessListController *tempV = [[WDBusinessListController alloc] init];
                
                __weak typeof (self)weakSelf = self;
                
                tempV.businessName = ^(NSString *name, NSString *businessID) {
                    
                    weakSelf.businessLabel.text = name;
                    
                    weakSelf.businessID = businessID;
                    
                };
                
                tempV.view.backgroundColor = WDBackColor;
                
                [self.navigationController pushViewController:tempV animated:YES];
            }
                break;
                
            default:
                break;
        }
    }
    
}

#pragma mark - <WDCustomSheetDelegate>
- (void)customSheet:(WDCustomSheet *)sheet clickButton:(NSUInteger)index
{
    self.refundLabel.text = self.termArr[index];
}

#pragma mark - textFiledDelegete
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.nameTextF) {//验证姓名
        
        if (string.length == 0) return YES;
        
        NSInteger existedLength = textField.text.length;
        
        NSInteger selectedLength = range.length;
        
        NSInteger replaceLength = string.length;
        
        if (existedLength - selectedLength + replaceLength > 20) {
            
            return NO;
        }
        
    } else if (textField == self.phoneTextF) {//验证手机
        
        if (string.length == 0) return YES;
        
        NSInteger existedLength = textField.text.length;
        
        NSInteger selectedLength = range.length;
        
        NSInteger replaceLength = string.length;
        
        if (existedLength - selectedLength + replaceLength > 11) {
            
            return NO;
        }
        
    } else {//预留其他
        return YES;
    }
    return YES;
}

- (void)valueChange:(id)sender
{
    
}

- (void)endEditing
{
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
